import axios from 'axios'
import { Spin } from 'antd';
import ReactDOM from 'react-dom/client'
axios.defaults.baseURL = 'http://localhost:5000'
let requestCount = 0
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    showLoading()
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    hideLoading()
    return response;
  }, function (error) {
    // Do something with response error
    hideLoading()
    return Promise.reject(error);
  });


  function showLoading () {
    if (requestCount === 0) {
        var dom = document.createElement('div')
        dom.setAttribute('id', 'loading')
        document.body.appendChild(dom)
        const root = ReactDOM.createRoot(dom)
        root.render(<Spin tip="Loading..." size="large" />)
    }
    requestCount++
  }

  function hideLoading () {
    requestCount--
    if (requestCount === 0) {
        document.body.removeChild(document.getElementById('loading') as HTMLElement)
    }
  }

  export default axios